var Facility = Facility || {};

Facility = function () {

			this.stageSize=null;
			this.centerOffset={x:1,y:1,z:1};
			this.zmesh=new THREE.Object3D;
			this.cursorMesh=null;this.facMesh=null;

			// this.projector = new THREE.Projector();
			this.goods={gid:null,position:{x:0,y:0,z:0},rotation:{x:0,y:0,z:0}};
			this.mouse2D = new THREE.Vector3();
			

};
// var me=this;
       // function	move(event){
		// this.mouse2D = new THREE.Vector3();
		// this.mouse2D.x = ( event.clientX / me.stageSize.width ) * 2 - 1;
		// this.mouse2D.y = - ( event.clientY / me.stageSize.height ) * 2 + 1;
		// console.warn(this.mouse2D)
		// // this.setMeshOnBoard(mouse2D,event.data.plane);
		// };
		
Facility.prototype = {

	constructor:Facility,
	
	initCursor:function(scene,div){
		
		cursorGeo = new THREE.CubeGeometry( 50, 20, 50 );
		this.centerOffset={x:50,y:20,z:50};
       cursorMaterial = new THREE.MeshBasicMaterial( { color: 0x123456, opacity: 0.5, transparent: true } );
       this.cursorMesh = new THREE.Mesh( cursorGeo, cursorMaterial );
       this.cursorMesh.name="cursor";

       scene.add(this.cursorMesh);
       // div.bind('mousemove',function(event){Facility.prototype.move(event);}); 
       

	},


	createMesh:function(goodsGeo,scene){
	  var me=this;

				var loader = new THREE.JSONLoader();
				scene.remove(this.cursorMesh);
				loader.load( goodsGeo.geometry, function( geometry ) {
					me.goods.gid=goodsGeo._id;
					
					
					geometry.computeBoundingBox();
        			me.centerOffset.x =  Math.round(geometry.boundingBox.x[ 1 ] - geometry.boundingBox.x[ 0 ]) ;
        			me.centerOffset.y =  Math.round(geometry.boundingBox.y[ 1 ] - geometry.boundingBox.y[ 0 ]) ;
        			me.centerOffset.z =  Math.round(geometry.boundingBox.z[ 1 ] - geometry.boundingBox.z[ 0 ]) ;
        			// console.log(me.centerOffset.x+","+me.centerOffset.y+","+me.centerOffset.z+";");
                rollOverMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } );
        
                matrials=new Array();
               	matrials.push(new THREE.MeshFaceMaterial());

                matrials.push(rollOverMaterial);
                 				
				position=me.cursorMesh.position;
				
				// me.cursorMesh = new THREE.Mesh( geometry, matrials );
				// me.cursorMesh.overdraw = true;
				// me.cursorMesh.name="fac";
				// me.cursorMesh.position=position;
				// scene.add(me.cursorMesh); 
				
				// rollOverGeo = new THREE.CubeGeometry( me.centerOffset.x, me.centerOffset.y, me.centerOffset.z );
				rollOverGeo = new THREE.CubeGeometry( 100, 100, 100 );
				rollOverMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } );
				me.cursorMesh = new THREE.Mesh( rollOverGeo, rollOverMaterial );
				me.cursorMesh.position=position;
				me.cursorMesh._id=goodsGeo._id;
				scene.add(me.cursorMesh); 
// 				
// 				
				// me.zmesh.add(zmesh2);
				// scene.add(me.zmesh); 
				});

             	
				// rollOverGeo = new THREE.CubeGeometry( 150, 50, 150 );
				// this.centerOffset={x:50,y:50,z:50};
				// rollOverMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } );
				// position=me.cursorMesh.position;
				// me.cursorMesh = new THREE.Mesh( rollOverGeo, rollOverMaterial );
				// me.cursorMesh.position=position;
				// scene.add(me.cursorMesh);


  },
  
  loadMesh:function(goodsGeo,goodsStyle,scene){
	  var me=this;
				console.warn(goodsStyle.position);
				var loader = new THREE.JSONLoader();
				scene.remove(this.cursorMesh);
				this.goods.gid=goodsGeo._id;
				loader.load( goodsGeo.geometry, function( geometry ) {

					
					// me.zmesh=new THREE.Object3D;
					geometry.computeBoundingBox();
        			me.centerOffset.x =  Math.round(geometry.boundingBox.x[ 1 ] - geometry.boundingBox.x[ 0 ]) ;
        			me.centerOffset.y =  Math.round(geometry.boundingBox.y[ 1 ] - geometry.boundingBox.y[ 0 ]) ;
        			me.centerOffset.z =  Math.round(geometry.boundingBox.z[ 1 ] - geometry.boundingBox.z[ 0 ]) ;
        			// console.log(me.centerOffset.x+","+me.centerOffset.y+","+me.centerOffset.z+";");
                rollOverMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } );
        
                matrials=new Array();
               	matrials.push(new THREE.MeshFaceMaterial());

                matrials.push(rollOverMaterial);
                 				
				
				me.facMesh = new THREE.Mesh( geometry, matrials );
				me.facMesh.overdraw = true;
				me.facMesh.name="fac";
				me.facMesh.position=goodsStyle.position;
				me.facMesh.rotation=goodsStyle.rotation;
				scene.add(me.facMesh); 
				// rollOverGeo = new THREE.CubeGeometry( me.centerOffset.x, me.centerOffset.y, me.centerOffset.z );
				// rollOverMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } );
				// me.cursorMesh = new THREE.Mesh( rollOverGeo, rollOverMaterial );
				// me.cursorMesh.position=position;
				// scene.add(me.cursorMesh); 
// 				
// 				
				// me.zmesh.add(zmesh2);
				// scene.add(me.zmesh); 
				});

             	
				// rollOverGeo = new THREE.CubeGeometry( 150, 50, 150 );
				// this.centerOffset={x:50,y:50,z:50};
				// rollOverMaterial = new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } );
				// position=me.cursorMesh.position;
				// me.cursorMesh = new THREE.Mesh( rollOverGeo, rollOverMaterial );
				// me.cursorMesh.position=position;
				// scene.add(me.cursorMesh);


  },
  
  setMesh:function(mesh){
    this.zmesh=mesh;
    // matrials=new Array();
    // matrials.push(cubeMaterial);
    // matrials.push( new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } ));
    mesh.materials.push(new THREE.MeshBasicMaterial( { color: 0xff0000, opacity: 0.5, transparent: true } ));    
    mesh.geometry.computeBoundingBox();
    this.centerOffset.x =  mesh.geometry.boundingBox.x[ 1 ] - mesh.geometry.boundingBox.x[ 0 ] ;
    if(this.centerOffset.x==0)this.centerOffset.x=1;
    this.centerOffset.y =  mesh.geometry.boundingBox.y[ 1 ] - mesh.geometry.boundingBox.y[ 0 ] ;
    if(this.centerOffset.y==0)this.centerOffset.y=1;
    this.centerOffset.z =  mesh.geometry.boundingBox.z[ 1 ] - mesh.geometry.boundingBox.z[ 0 ] ;
    if(this.centerOffset.z==0)this.centerOffset.z=1;
  },
	
	move:function(event){
		this.mouse2D = new THREE.Vector3();
		this.mouse2D.x = ( event.clientX / this.stageSize.width ) * 2 - 1;
		this.mouse2D.y = - ( event.clientY / this.stageSize.height ) * 2 + 1;
		// this.setMeshOnBoard(mouse2D,event.data.plane);
	},
	
	setMeshOnBoard:function(plane,scene,camera,objects){
		// mouse3D = this.projector.unprojectVector( mouse2D.clone(), this.camera );
		projector = new THREE.Projector();
		ray = projector.pickingRay( this.mouse2D.clone(),camera );
        // var ray = new THREE.Ray( this.camera.position, mouse3D.subSelf( this.camera.position ).normalize() );

		// this.setPosition(mouse3D);
        var intersects = ray.intersectScene( scene );
        
		
        if ( intersects.length > 0 ) {
          
          intersector = this.getRealIntersector( intersects,plane,objects );
          if ( intersector ) {
          	
			       this.setPosition( intersector );

          }

        }
        
        
	},
	
	locate:function(event){
	  // alert(event.data.objects.length);
	  // this.goods.position=this.zmesh.position;
	  // this.goods.rotation=this.zmesh.rotation;
	  
	  this.goods.position.x=this.cursorMesh.position.x;
	  this.goods.position.y=this.cursorMesh.position.y;
	  this.goods.position.z=this.cursorMesh.position.z;
	  this.goods.rotation.x=this.cursorMesh.rotation.x;
	  this.goods.rotation.y=this.cursorMesh.rotation.y;	
	  this.goods.rotation.z=this.cursorMesh.rotation.z;		
	  
	  
		// var ray = new THREE.Ray( this.zmeshithis.goods.rotation.x=this.zmesh.rotation.x;	s.zmesh.position, new THREE.Vector3(0,0,1) );
		// 
		//     var c = THREE.Collisions.rayCastNearest(ray);
		//         
		//       if (c && c.distance == -1) {
		//           alert("Colliding!");
		//           c.mesh.materials[0].color = new THREE.Color(0xff0000);
		//           return;
		//         } 
		//         // else if(c && c.distance >= 0) {
		//         //   info.innerHTML = "Approaching @ " + c.distance;
		//         // } else {
		//         //   info.innerHTML = "No collider in sight.";
		//         // }


                
		// THREE.Collisions.colliders.push( THREE.CollisionUtils.MeshOBB(this.zmesh) );
		// this.zmesh.materials.pop();
	},
	
	rotate:function(event){
	  // alert(event.which);
	  // switch(event.which){
	    // case 68://D right
	     // this.zmesh.rotation.x+=30;
	     // break;
	    // case 65://a left
	     // this.zmesh.rotation.y=event.data.value;
	     // break;
	    // case 91://w up
	     // this.zmesh.rotation.z=event.data.value;
	     // break;
	  // }
	  // alert(event.data.curmouse.x);
	  
	  if(event.clientX>event.data.curmouse.x){
	  	this.cursorMesh.rotation.y+=.01*(event.clientX-event.data.curmouse.x);
	  	
	  }
	  if(event.clientX<event.data.curmouse.x){
	  	this.cursorMesh.rotation.y+=.01*(event.clientX-event.data.curmouse.x);
	  	
	  }
	  if(event.clientY>event.data.curmouse.y){
	  	this.cursorMesh.rotation.x+=.01*(event.clientY-event.data.curmouse.y);
	  	
	  }
	  if(event.clientY<event.data.curmouse.y){
	  	this.cursorMesh.rotation.x+=.01*(event.clientY-event.data.curmouse.y);
	  	
	  }
	  event.data.curmouse.x=event.clientX;
	  event.data.curmouse.y=event.clientY;
	  // switch(event.data.dic){
	  	// case "left":
	  	// this.zmesh.rotation.y+=.1;
	  	// break;
	  // }
		
	},
	
	isEmbeded:function(Collisions){


        var ray = new THREE.Ray( this.zmesh.position, new THREE.Vector3(0,0,1) );
        var c = Collisions.rayCastNearest(ray);
        if (c && c.distance == -1) {
          info.innerHTML = "Colliding!";
          c.mesh.materials[0].color = new THREE.Color(0xff0000);
        }
	},
	
	isCollided:function(event){
	     // mouse2D = new THREE.Vector3();
	     //        mouse2D.x = ( event.clientX / event.data.stageSize.width ) * 2 - 1;
	     //        mouse2D.y = - ( event.clientY / event.data.stageSize.height ) * 2 + 1;
	     // mouse3D = this.projector.unprojectVector( mouse2D.clone(), this.camera );
	     //        var ray = new THREE.Ray( this.camera.position, mouse3D.subSelf( this.camera.position ).normalize() );
	     //        
	     //        inMeshs=ray.intersectObjects(event.data.objects);
	     //        if ( inMeshs.length > 0 ) {
	     //             alert("meshs is Collided");
	     //             return true;
	     //         }else{
	     //             return false;
	     //         } 

            for(var i in this.zmesh.geometry.vertices){
                  //var position = this.zmesh.geometry.vertices[i].position.addSelf(this.zmesh.position);
                  var position=new THREE.Vector3;
                  
                  // x=this.zmesh.geometry.vertices[i].position.x*Math.cos(45);
                  // y=this.zmesh.geometry.vertices[i].position.y*Math.sin(45);
                  x=this.zmesh.geometry.vertices[i].position.x;
                  y=this.zmesh.geometry.vertices[i].position.y;
                  z=this.zmesh.geometry.vertices[i].position.z;
                  var p2=new THREE.Vector3(x,y,z);
                  //this.zmesh.geometry.vertices[i].position.x*Math.cos(this.zmesh.rotation.x);
                  position.add(p2,this.zmesh.position);
                  // var ray = new THREE.Ray( this.camera.position, mouse3D.subSelf( this.camera.position ).normalize() );
                  var ray = new THREE.Ray( position, new THREE.Vector3( 0, 0, 1 ) );
                  inMeshs=ray.intersectObjects(event.data.objects);
                  // //var position = this.zmesh.geometry.vertices[i].position;
                  // var ray = new THREE.Ray( position, new THREE.Vector3(0,0,1) );
                  // 
                  var c = THREE.Collisions.rayCastNearest(ray);
                  if (c && c.distance == -1) {
                     console.log("Colliding!");
                      c.mesh.materials[0].color = new THREE.Color(0xff0000);
                      return;
                  } else if(c && c.distance >= 0) {
                      console.log( "Approaching @ " + c.distance +"; i="+i);
                  } else {
                      console.log( "No collider in sight.");
                  }
                }
	},
	
	setPosition:function (intersector ) {
		var tmpVec = new THREE.Vector3();
		var voxelPosition = new THREE.Vector3();
		if(intersector==null){
			alert('test');
		}
        tmpVec.copy( intersector.face.normal );
        voxelPosition.add( intersector.point, intersector.object.matrixRotationWorld.multiplyVector3( tmpVec ) );
        // console.warn(voxelPosition);
		voxelPosition.x = Math.floor( voxelPosition.x / this.centerOffset.z ) * this.centerOffset.z + this.centerOffset.z/2;
		// voxelPosition.y = Math.floor( voxelPosition.y / this.centerOffset.y ) * this.centerOffset.y + this.centerOffset.y/2;
		voxelPosition.z = Math.floor( voxelPosition.z / this.centerOffset.x ) * this.centerOffset.x + this.centerOffset.x/2;


			this.cursorMesh.position=voxelPosition;
			this.cursorMesh.updateMatrix();

     },
     getRealIntersector:function(intersects,flat,objects){
		var isInObj=false;
		for( i = 0; i < intersects.length; i++ ) {
	          intersector = intersects[ i ];
 			if ( intersector.object !=this.cursorMesh) {

            	return intersector;


			}


        }

        return null;
     },
     test:function(){
     	alert('ddd');
     }
	
};